<?php
/**
 * yyhr company info.
 */
JLoader::register('ProvinceHelper', JPATH_SITE.'/components/com_city/helper.php');

const PIPAPAI_COMPANY_NAME = '南京枇杷派网络科技有限公司';
const PIPAPAI_BANK = '中国银行南京城南支行';
const PIPAPAI_BANK_ACCOUNT = '4728 6063 3432';
const PIPAPAI_SUPPORT_PHONE = '4006-747247';
const PIPAPAI_SUPPORT_EMAIL = 'support@pipapai.com';

/**
 * yyhr permissions.
 */
const PERMISSION_VIEW_SHARED = 0x01;
const PERMISSION_VIEW_ALL = 0x02;
const PERMISSION_JOB_CRUD = 0x04;
const PERMISSION_JOB_ADMIN_ALL = 0x08;
const PERMISSION_JOB_ADMIN_ASSIGNED = 0x10;

/**
 * encrpt key/iv 
 */
const CRYPTKEY = '1P00ml4R0ck$!pai';
const CRYPTIV = '3345708913246756';

class PCompanyHelper
{
   public static function getHomeLink() {
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();

      $query = "SELECT sub_domain FROM #__jobs_employer WHERE user_id=" . $user->id;
      $db->setQuery($query);
      $sub_domain = $db->loadResult();

      if (!empty($sub_domain)) {
         $homeLink = 'http://' . trim($sub_domain). '.'.PUtil::serverDomain();
      } else {
         $homeLink = 'http://' . trim($user->id) . '.'.PUtil::serverDomain();
      }

      return $homeLink;
   }

   public static function showValidateStatus($user, $always=false) {
      if($user->validated == EMPLOYER_VALIDATED) {
         $iknow_validated = JRequest::getString('iknow_validated', null, 'cookie');
         if($always || ($user->validate_datetime >= $user->cb_lastlogondate && !$iknow_validated))
            echo '<div class="hr_note iknowtext" id="validate_note">
                      <div class="hr_innernote">
                        <div class="hr_note_content medium">您的公司已通过验证。如有变更，请上传您最新年检的营业执照副本。<span class="iknow" data-cookie="365" data-cookiename="iknow_validated"><a href="javascript:;">我知道了</a></span></div>
                     </div>
                     <div class="hr_note_btm"></div>
                  </div>';
      }
      elseif($user->validated == EMPLOYER_VALIDATING) {
         $iknow_validating = JRequest::getString('iknow_validating', null, 'cookie');
         if($always || ($user->validate_datetime >= $user->cb_lastlogondate && !$iknow_validating))
            echo '<div class="hr_note iknowtext" id="validate_note">
                      <div class="hr_innernote">
                        <div class="hr_note_content medium">您公司的验证正在进行中，请等待一个工作日完成验证。<span class="iknow" data-cookie="365" data-cookiename="iknow_validating"><a href="javascript:;">我知道了</a></span></div>
                     </div>
                     <div class="hr_note_btm"></div>
                  </div>';
      }
      elseif($user->validated == EMPLOYER_FAIL_VALIDATION) {
         echo '<div class="hr_note iknowtext" id="validate_note">
                      <div class="hr_innernote">
                        <div class="hr_note_content medium">您公司的验证失败: ' . $user->validate_msg . '</div>
                     </div>
                     <div class="hr_note_btm"></div>
                  </div>';
      }
      else {
         $iknow = JRequest::getString('iknow_validate', null, 'cookie');
         if($always || !$iknow) {
           echo '<div class="hr_note iknowtext" id="validate_note">
                      <div class="hr_innernote">
                        <div class="hr_note_content hr_note_oneline medium">您的公司尚未通过验证，部分功能无法使用。<a href="'.
                        OC_Helper::linkToRoute('company_license').'" style="color:#ff6600;">立即验证</a>&nbsp;&nbsp;<a class="iknow" data-cookiename="iknow_validate" href="javascript:;">我知道了</a></div>
                     </div>
                     <div class="hr_note_btm"></div>
                  </div>';
         }

      }
   }

   public static function showNavigationMenu($masteruser=false, $activeitem='') {
      //get company's validated status
      $user = PFactory::getMasterUser();
      $user = JobHelper::getEmployerProfileDetails($user->id);
      $validated = $user->validated;
   ?>
      <?php if($masteruser):?>
      <li<?php echo $activeitem=='basicinfo' ? ' class="cur_li"': ''; ?>>
         <a href="<?php echo $activeitem!='basicinfo' ? OC_Helper::linkToRoute('company_basicinfo') : '#';?>">公司信息</a>
      </li>
      <li<?php echo $activeitem=='summary' ? ' class="cur_li"': ''; ?>>
         <a href="<?php echo $activeitem!='summary' ? OC_Helper::linkToRoute('company_summary') : '#';?>">公司概况</a>
      </li>
      <li<?php echo $activeitem=='logo' ? ' class="cur_li"': ''; ?>>
         <a href="<?php echo $activeitem!='logo' ? OC_Helper::linkToRoute('company_logo') : '#'; ?>">公司LOGO</a>
      </li>
      <li<?php echo $activeitem=='license' ? ' class="cur_li"': ''; ?>>
         <a href="<?php echo $activeitem!='license' ? OC_Helper::linkToRoute('company_license') : '#'; ?>">公司验证</a>
      </li>
      <?php endif; ?>
      <?php if($masteruser):?>
      <li<?php echo $activeitem=='changepassword' ? ' class="cur_li"': '';?>>
        <a href="<?php echo $activeitem!='changepassword' ? OC_Helper::linkToRoute('company_changepassword') : '#'; ?>">修改密码</a>
      </li>
      <?php else: ?>
      <li<?php echo $activeitem=='changepassword' ? ' class="cur_li"': '';?>><a href="<?php echo OC_Helper::linkToRoute('company_changepassword'); ?>">修改密码</a></li>
      <?php endif; ?>
      <li<?php echo $activeitem=='synchronousinfo' ? ' class="cur_li"': ''; ?>>
         <a href="<?php echo $activeitem!='synchronousinfo' ? OC_Helper::linkToRoute('company_synchronousinfo') : '#'; ?>">同步信息</a>
      </li>
      
      <?php if($masteruser): ?>
      <?php if(0): ?>
      <!-- <li<?php echo $activeitem=='cloudspace' ? ' class="cur_li"': ''; ?>>
         <a href="<?php echo $activeitem!='cloudspace' ? OC_Helper::linkToRoute('company_cloudspace') : '#'; ?>">云端储存</a>
      </li> -->
      <?php endif; ?>
      <?php if(isDevMode() || $validated==EMPLOYER_VALIDATED):?>
      <li<?php echo $activeitem=='subaccounts' ? ' class="cur_li"': ''; ?>>
         <a href="<?php echo $activeitem!='subaccounts' ? OC_Helper::linkToRoute('company_subaccounts') : '#'; ?>">子账号</a>
      </li>
      <li<?php echo $activeitem=='quota' ? ' class="cur_li"': ''; ?>>
         <a href="<?php echo $activeitem!='quota' ? OC_Helper::linkToRoute('company_quota') : 'javascript:;'; ?>">增值服务</a>
      </li>
      <li<?php echo $activeitem=='emailsms' ? ' class="cur_li"': ''; ?>>
         <a href="<?php echo $activeitem!='emailsms' ? OC_Helper::linkToRoute('company_emailsms') : 'javascript:;'; ?>">短信邮件设置</a>
      </li>
      <?php endif;?>
      <?php endif; ?>

   <?
   }

   public static function showCompanyAvatar($avatar, $avatarapproved) {
      if ($avatar && $avatarapproved) {
         $avatarLink = "/images/comprofiler/".$avatar;
      } else {
         $avatarLink = "/images/company_128x128.gif";
      }

      return $avatarLink;
   }

   public static function validateCompanyRegistration() {
      $user = PFactory::getMasterUser();
      $user = JobHelper::getEmployerProfileDetails($user->id);

      // just random validation check 
      if($user->id_city && $user->id_comp_type && $user->id_size_type && strlen($user->phone) > 0) {
         return true; 
      }

      return false; 
   }
   
   /* resume forwarding email */
   public static function getResumeForwardEmail() {
      $user = PFactory::getMasterUser();
   
      $db = PFactory::getDbo();
   
      $query = "SELECT email FROM *PREFIX*hr_email WHERE company_id=" . $user->id;
      $db->setQuery(PUtil::replaceOCPrefix($query));
   
      return $db->loadResult();
   }
   
   public static function getJobManagerList($jobid = 0) {
      $appid = JRequest::getString('appid', '');
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();
      $query = "SELECT u.displayname, ue.uid, IF(jm.jobid IS NOT NULL, 1, 0) AS admin FROM *PREFIX*users_extended AS ue " .
               " LEFT JOIN *PREFIX*users AS u ON u.uid=ue.uid " .
               " LEFT JOIN *PREFIX*hr_jobmanager AS jm ON (jm.manager=ue.uid AND jm.jobid=" . intval($jobid) . ")" .
               " WHERE ue.block=0 AND ue.deleted=0 " . ($appid == 'reports' ? "" : "AND !(ue.permissions & " . PERMISSION_JOB_ADMIN_ALL . ")") . " AND ue.owner=" . $user->id;
      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadAssocList();
   }
  
   public static function getSubUserMaster($uid='') {
      $db = PFactory::getDbo();
      $query = "SELECT owner FROM *PREFIX*users_extended
                WHERE uid = " . $db->quote($uid); 
      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadResult();
   }
 
   public static function getSubUser() {
      $db = PFactory::getDbo();
      $db->setQuery("SET @@SESSION.group_concat_max_len = ". 1024*1024);
      $db->query();

      $query = "SELECT ue.*, GROUP_CONCAT(hj.jobid) AS assignedjobs"  . 
               " FROM *PREFIX*hr_jobmanager AS hj " .
               " LEFT JOIN *PREFIX*users_extended AS ue ON ue.uid=hj.manager " .
               " LEFT JOIN *PREFIX*users AS u ON u.uid=ue.uid " .
               " WHERE ue.block=0 AND ue.deleted=0 AND u.uid = " . $db->quote(OC_User::getUser());
      /* try to load from cache */
      $cache = CacheHelper::getCache('app_company');
      // get cached data now 
      $data = $cache->call(array('PCompanyHelper', '_getSubUser'), $db->useLastConnection($query));

      CacheHelper::setTriggers(OC_User::getUser(), $cache, array('*PREFIX*hr_jobmanager', '*PREFIX*users_extended'));
      return $data;
   }

   public static function _getSubUser($query) {
      $db = PFactory::getDbo();
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $subuser = $db->loadObject(); 
      $subuser->assignedjobs = $subuser->assignedjobs ? explode(',', $subuser->assignedjobs) : array();
      return $subuser;
   }

   public static function getAllJobIds() {
      $master_uid = PFactory::getMasterUser()->get("id");
      $query = "SELECT DISTINCT id FROM #__jobs_job WHERE employer_id =  ".intval($master_uid);
      // Try to load from cache
      // $cache = CacheHelper::getCache('app_company');
      // // Cache all jobids
      // $jobids = $cache->call(array('PCompanyHelper', '_getAllJobIds'), $query);

      // CacheHelper::setTriggers($master_uid, $cache, array('#__jobs_job'));
      return self::_getAllJobIds($query);
   }

   public static function _getAllJobIds($query) {
      $db = PFactory::getDbo();
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $jobids = $db->loadAssocList('', 'id');
      return $jobids;
   }
   
   public static function ownJobId($jobid) {
      $jobids = self::getAllJobIds();
      if ( !in_array($jobid, $jobids) ) {
         return false;
      }

      return true; 
   }

   public static function getUserQuota($user_id = '') {
      if (empty($user_id))
         $user_id = PFactory::getMasterUser()->id;
      
      $db = PFactory::getDbo();
      $query = "SELECT qt.id AS type_id, qt.qtype, qt.title, qt.default_quota, qt.sms_unit_price, " .
               " uq.quota AS user_quota, uq.order_count, uq.sms_num, uq.sms_left, uq.expired, " .
               " ess.settings AS email_sms_settings, je.num_subaccounts, je.num_jobseekers "  .
               " FROM #__user_quota AS uq " .
               " LEFT JOIN #__quota_types AS qt ON qt.id=uq.type_id " .
               " LEFT JOIN #__email_sms_settings AS ess ON ess.user_id=uq.user_id " .
               " LEFT JOIN #__jobs_employer AS je ON je.user_id=uq.user_id " .
               " WHERE uq.user_id=" . intval($user_id);
      /* try to load from cache */
      $cache = CacheHelper::getCache('app_company');
      // get cached data now
      $data = $cache->call(array('PCompanyHelper', '_getUserQuota'), $query);
   
      CacheHelper::setTriggers($user_id, $cache, array('#__user_quota', '#__email_sms_settings', '#__jobs_employer'));
      return $data;
   }
   
   public static function _getUserQuota($query) {
      $db = PFactory::getDbo();
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $userQuota = $db->loadAssoc();
      
      if (empty($userQuota)) {
         // create default quota
         $sql = "INSERT IGNORE INTO #__user_quota (user_id, type_id) SELECT " . intval(PFactory::getMasterUser()->id) . " AS user_id, id FROM #__quota_types WHERE isfree=1";
         $db->setQuery($sql);
         $db->execute();
         
         $db->setQuery(PUtil::replaceOCPrefix($db->useLastConnection($query)));
         $userQuota = $db->loadAssoc();
      }
      
      $default_quota = empty($userQuota['default_quota']) ? array() : json_decode($userQuota['default_quota'], true);
      $user_quota = empty($userQuota['user_quota']) ? array() : json_decode($userQuota['user_quota'], true);
      $userQuota['quota'] = array_merge($default_quota, $user_quota);
      if (empty($userQuota['email_sms_settings'])) {
         $userQuota['email_sms_settings'] = array(
            'email_jobstatus_weekly'     => '0,1,2,3,4,5,6',
            'email_jobsaved'             => 0,
            'email_remind_event_owner'   => 1,
            'sms_onlineinterview_0h'     => 0,
            'sms_onlineinterview_48h'    => 1,
            'sms_offlineinterview_0d'    => 0,
            'sms_offlineinterview_1d'    => 1,
            'sms_offer_0d'               => 0,
            'sms_offer_1d'               => 1
         );
      } else {
         $userQuota['email_sms_settings'] = json_decode($userQuota['email_sms_settings'], true);
      }
      return $userQuota;
   }
   
   public static function getQuotaEvent($etype) {
      $db = PFactory::getDbo();
      $query = "SELECT title, content FROM #__quota_events WHERE UTC_TIMESTAMP()>start_date AND UTC_TIMESTAMP()<end_date AND published=1 AND etype=" .$db->quote($etype);
      $db->setQuery($query);
      return $db->loadObject();
   }
   
   public static function checkQuotaEnable() {
      $db = PFactory::getDbo();
      $query = "SELECT COUNT(*) FROM #__quota_types WHERE enable=1";
      /* try to load from cache */
      $cache = CacheHelper::getCache('app_company');
      // get cached data now
      $data = $cache->call(array('PCompanyHelper', '_checkQuotaEnable'), $query);
       
      CacheHelper::setTriggers(0, $cache, array('#__quota_types'));
      return $data;
   }
   
   public static function _checkQuotaEnable($query) {
      $db = PFactory::getDbo();
      $db->setQuery($query);
      return $db->loadResult() > 0 ? true : false;
   }
   
   public static function isJobManager() {
      if(OC_User::getUser() === false)
         return false;
   
      $user = PFactory::getUser();
      if(!$user->get("guest") && $user->get("id") > 0)
         return true;
   
      /* a subaccount, we need check read permissions */
      $subuser = self::getSubUser();
      if(empty($subuser))
         return false; 

      return $subuser->permissions & PERMISSION_VIEW_ALL;
   }
   
   public static function isJobManagerViewOnly() {
      if(OC_User::getUser() === false)
         return false;
       
      $user = PFactory::getUser();
      if(!$user->get("guest") && $user->get("id") > 0)
         return false;
       
      /* check if session cached */
      $subuser = self::getSubUser();
      if(empty($subuser))
         return false; 

      return $subuser->permissions & PERMISSION_VIEW_ALL && 
             !($subuser->permissions & PERMISSION_JOB_ADMIN_ALL) && 
             !($subuser->permissions & PERMISSION_JOB_ADMIN_ASSIGNED); 
   }
   
   public static function checkJobManagerPermissions($jobid) {
      if ( OC_User::getUser() === false )
         return false;

      if ( empty($jobid) )
         return false;

      if(!self::ownJobId($jobid))
         return false; 

      $user = PFactory::getUser();
      if(!$user->get("guest") && $user->get("id") > 0)
         return true;

      /* a subaccount, we need check job admin permissions */
      $subuser = self::getSubUser();
      if (!empty($subuser)) {
         if ($subuser->permissions & PERMISSION_JOB_ADMIN_ALL) {
            return true;
         } elseif ($subuser->permissions & PERMISSION_JOB_ADMIN_ASSIGNED) {
            $assignedjobs = $subuser->assignedjobs;
            return in_array($jobid, $assignedjobs) ? true : false;
         }
      }

      return false;
   }

   public static function checkJobsManagerPermissions($jobids = array(), $manager = true){
      if(empty($jobids))
         return null;

      $isMasterUser = PFactory::isMasterUser();
      $checkManager = $isMasterUser ? false : $manager;

      $db = PFactory::getDbo();
      $query = 'SELECT jj.id FROM #__jobs_job AS jj ' .
            ($checkManager ? 'LEFT JOIN *PREFIX*hr_jobmanager AS jm ON (jm.jobid=jj.id AND jm.manager=' . $db->quote(OC_User::getUser()) . ')' : '') .
            'WHERE jj.employer_id=' . intval(PFactory::getMasterUser()->id) . ' AND jj.id IN (' . implode(',', $jobids) . ')' . ($checkManager ? ' AND jm.jobid IS NOT NULL' : '');
      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadAssocList('', 'id');
   }

   public static function checkCRUDPermission() {
      $permissionCheck = true;
       
      if (!PCompanyHelper::isJobManager()) {
         $permissionCheck = false;
      } else {
         if(!PFactory::isMasterUser()) {
            $subUser = PCompanyHelper::getSubUser();
            if (!(isset($subUser->permissions) && $subUser->permissions & PERMISSION_JOB_CRUD)) {
               $permissionCheck = false;
            }
         }
      }
      
      return $permissionCheck;
   }
   
   public static function checkAdminAllPermission() {
      $permissionCheck = true;
       
      if (!PCompanyHelper::isJobManager()) {
         $permissionCheck = false;
      } else {
         if(!PFactory::isMasterUser()) {
            $subUser = PCompanyHelper::getSubUser();
            if (!(isset($subUser->permissions) && $subUser->permissions & PERMISSION_JOB_ADMIN_ALL)) {
               $permissionCheck = false;
            }
         }
      }
   
      return $permissionCheck;
   }
   
   public static function getJobAdminUser($jobid = 0, $limit = 0) {
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();
      $query = "SELECT u.displayname, ue.uid FROM *PREFIX*users_extended AS ue " .
               " LEFT JOIN *PREFIX*users AS u ON u.uid=ue.uid " .
               " LEFT JOIN *PREFIX*hr_jobmanager AS jm ON (jm.manager=ue.uid AND jm.jobid=" . intval($jobid) . ")" .
               " WHERE ue.block=0 AND ue.deleted=0 AND jm.jobid IS NOT NULL AND !(ue.permissions & " . PERMISSION_JOB_ADMIN_ALL . ") AND ue.owner=" . $user->id;
      
      if(!empty($limit)) {
         $query .= " limit $limit ";
      }
      
      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadAssocList();
   }
   
   public static function getJobAdminAllUser() {
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();
      $query = "SELECT ue.uid FROM *PREFIX*users_extended AS ue
                WHERE ue.block=0 AND ue.deleted=0 AND ue.permissions & " . $db->quote(PERMISSION_JOB_ADMIN_ALL) . " AND ue.owner=" . $user->id;
      $db->setQuery(PUtil::replaceOCPrefix($query));
      return $db->loadObjectList();
   }
   
   public static function setSubUserLastLogonDate($uid) {
      $db = JFactory::getDbo();
      $query = "UPDATE *PREFIX*users_extended SET lastvisitDate=UTC_TIMESTAMP WHERE uid= " . $db->quote($uid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $db->execute();
   }

   public static function updateSubUserActiveDate($uid) {
      $db = JFactory::getDbo();
      $query = "UPDATE *PREFIX*users_extended SET lastactiveDate=UTC_TIMESTAMP WHERE uid= " . $db->quote($uid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $db->execute();
   }
   
   public static function updateJobManager() {
      $user = PFactory::getMasterUser();
      $db = PFactory::getDbo();
      $query = "SELECT COUNT(*) FROM #__jobs_job AS jj WHERE jj.is_active='y' AND jj.id NOT IN (SELECT jobid FROM *PREFIX*hr_jobmanager GROUP BY jobid) AND jj.employer_id=" . $user->id;
      $db->setQuery(PUtil::replaceOCPrefix($query));
      
      if ($db->loadResult() <= 0)
         return true;
      
      $query = "INSERT IGNORE INTO *PREFIX*hr_jobmanager (jobid, manager)
                SELECT jj.id AS jid, ue.uid FROM *PREFIX*users_extended AS ue 
                LEFT JOIN *PREFIX*users AS u ON u.uid=ue.uid 
                LEFT JOIN #__jobs_job AS jj ON (jj.is_active='y' AND jj.employer_id=" . $user->id . ")
                LEFT JOIN *PREFIX*hr_jobmanager AS jm ON jm.jobid=jj.id AND jm.manager=ue.uid
                WHERE ue.block=0 AND ue.deleted=0 AND ue.permissions & " . $db->quote(PERMISSION_JOB_ADMIN_ALL) . " AND ue.owner=" . $user->id . " AND jm.jobid IS NULL";
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $db->execute();
     
      // Event Driven Cache/Object Caching - clear any cache related to affected tables 
      CacheHelper::triggerRemove($user->id, array('*PREFIX*hr_jobmanager'));
 
      return true;
   }

   public static function checkCompanyValidateStatus($currentapp) {
      static $validated = null;
      if(!OC_User::isLoggedIn())
         return;
      if($validated === null){
         $user = PFactory::getMasterUser();
         $user = JobHelper::getEmployerProfileDetails($user->id);
         $validated = $user->validated;
      }      
      if($validated == EMPLOYER_VALIDATED) 
         return;    
      $allowed = array("账户设置","企业中心");    
      if(in_array($currentapp, $allowed) !== false)
         return; 
      if(PFactory::isMasterUser()){
         OC_Response::redirect (OC_Helper::linkToRoute("company_license"));
      }else{
         OC_Response::redirect (OC_Helper::linkToRoute("company_home"));
      }	           
      exit(); 
   }

   public static function encrypt($text) {
      if(empty($text))
         return $text; 

      $blocksize = 16;
      $pad = $blocksize - (strlen($text) % $blocksize);
      $text = $text . str_repeat(chr($pad), $pad);
      return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, CRYPTKEY, $text, MCRYPT_MODE_CBC, CRYPTIV));
   }

   public static function decrypt($text) {
      if(empty($text))
         return $text; 
      return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, CRYPTKEY, base64_decode($text), MCRYPT_MODE_CBC, CRYPTIV));
   }
  
   public static function isJobAdmin() {
      if(OC_User::getUser() === false)
         return false;
      $user = PFactory::getUser();
      if(!$user->get("guest") && $user->get("id") > 0)
         return true;
      /* check if session cached */
      $subuser = self::getSubUser();
      if(empty($subuser))
         return false;
      return ($subuser->permissions & PERMISSION_JOB_ADMIN_ALL) ||
             ($subuser->permissions & PERMISSION_JOB_ADMIN_ASSIGNED);
   }

   public static function getSyncStatus($type='', $thirdaccount_status, $from=false) {

      if(empty($type) || empty($thirdaccount_status))
         return null; 

      $sync_title = '';
      $sync_status = '';
      switch($type) {
         case 'fetchjobs':
            $sync_title = '下载职位信息并开始自动接收简历';
            $result = $thirdaccount_status['result'];
            if($result != 'captcha') {
               if(!empty($thirdaccount_status['msg'])) {
                  $sync_title = $thirdaccount_status['msg'];
               } else {
                  if (!empty($thirdaccount_status['time'])) {
                     $sync_title = JHtml::_('date', $thirdaccount_status['time'], 'Y-m-d H:i:s') . " 同步成功";
                  } else {
                     $sync_title = "账号已同步";
                  }
               }
            }
            if($result == 'success' || $result == 'error'){
               if($from)
                  $sync_status = 'syc_iconsown_' . $result;
               else
                  $sync_status = 'config_' . $result;
            }
         break;

         case 'importresumes':
            $sync_title = '导入人才夹中的所有简历';
            $result = $thirdaccount_status['result'];
            if($result != 'captcha') {
               if(!empty($thirdaccount_status['msg'])) {
                  $sync_title = $thirdaccount_status['msg'];
               } else {
                  if (!empty($thirdaccount_status['time'])) {
                     $sync_title = JHtml::_('date', $thirdaccount_status['time'], 'Y-m-d H:i:s') . " 导入成功";
                  } else {
                     $sync_title = "导入成功";
                  }
               }
            }
            if($result == 'success' || $result == 'error' || $result == 'syncing')
               $sync_status = 'config_' . $result;

         break; 
      }
      return array($sync_title, $sync_status);
   }

   public static function getSelectJobTitle($folder_id) {
      if(empty($folder_id))
         return null;

      if(PFactory::isMasterUser()){
         $user_id = PFactory::getMasterUser()->id;
      }else{
         $user_id = OC_User::getUser();
      }

      $curcityids = array();
      $selectedTitle = "";
      $curfolderid = "";

      if (!empty($folder_id)) {
         $dirInfo = PJobpositionHelper::getDirInfo($folder_id, $user_id);

         if(isset($dirInfo['data'])){
            $data = json_decode($dirInfo['data'],true);
            if(!empty($data['cityids']) && (!isset($data['custom']) ||  $data['custom'] == false)){
               $selectedTitle = '地区-';
               $curcityList = PResumesHelper::getJobCityList(PFactory::getMasterUser()->id, false, '', $data['cityids']);
               if (!empty($curcityList)) {
                  $cText = array();
                  $curcityids = array_keys($curcityList);
                  foreach ($curcityList as $c) {
                     $cText[] = (ProvinceHelper::getMuniProvinceId($c['cityid']) ? $c['province'] : $c['province'] . $c['city']);
                  }
                  $selectedTitle .= implode(',', $cText);
               }else {
                  $selectedTitle = '地区不存在';
               }
            }else if(!empty($data['folderid']) && (!isset($data['custom']) ||  $data['custom'] == false)){
               $curfolderid = $data['folderid'];
               if($data['folderid'] == -1){
                  $selectedTitle = "文件夹-全部职位";
               }else{
               	  $dirInfo2 = PJobpositionHelper::getDirInfo($data['folderid'], $user_id);
               	  if(!empty($dirInfo2))
               	     $selectedTitle = '文件夹-' . $dirInfo2['foldername'];
               }
            }else{
               $selectedTitle = "自定义-" . $dirInfo['num']. "个职位";
            }
         }
      }
      return array($selectedTitle,$curcityids,$curfolderid);
   }

   public static function getAutoRenewfolderid() {
      $db = PFactory::getDbo();
      $query = "SELECT type,folder_id FROM *PREFIX*hr_job_folder where owner = ".$db->quote(OC_User::getUser());
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $folderdata = $db->loadAssocList();

      $folderid = array();
      foreach($folderdata as $k => $v){
         $folderid[$v['type']] = $v['folder_id'];
      }
      return $folderid;
   }

   public static function getAutoActionsStatus($password,$thirdaccounts_status) {
      if(empty($password) || empty($thirdaccounts_status))
         return false;

      if(!empty($password)){
         if(!empty($thirdaccounts_status['fetchjobs']['result'])){
            return true;
         }elseif (!empty($thirdaccounts_status['result'])){
            return true;
         }
      }
      return false;
   }
}

